// ============================== 导入依赖 ============================== //

import VueRouter from 'vue-router'

const routes = []
const imports = require.context('./', false, /^\.\/(?!index).+js$/)
imports.keys().forEach((path) => routes.push(imports(path).default))
routes.push({ path: '*', redirect: '/' })

// ============================== 导出路由 ============================== //

const router = new VueRouter({ mode: 'history', base: 'screen', routes })

export default router

// ============================== 路由拦截 ============================== //

router.beforeEach((to, from, next) => {
  if (sessionStorage.TOKEN) next()
  else location = `${location.origin}/login?redirect=/screen${to.fullPath}`
})

// ============================== 异常处理 ============================== //

const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return VueRouterPush.call(this, location).catch((err) => err)
}

const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return VueRouterReplace.call(this, location).catch((err) => err)
}
